<template>
	<a-drawer :title="formData.id ? '编辑用户' : '增加用户'" :width="620" :visible="visible" :destroy-on-close="true"
		:body-style="{ paddingBottom: '80px', 'padding-top': '0px' }" :footer-style="{ textAlign: 'right' }"
		@close="onClose">
		<a-form :model="searchForm" layout="vertical" style="margin-top: 30px;">
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="账号：">
						<a-input v-model:value="searchForm.account" placeholder="请输入账号" allow-clear
							@input="debouncedHandleBlur" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="组织：">
						<a-select v-model:value="searchForm.deptId" :options="treeData" :filter-option="filterOption"
							show-search :field-names="{ label: 'orgName', value: 'deptId' }" style="width: 100%"
							placeholder="请选择组织" @change="handleBlur" allow-clear>
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="选择用户：">
						<a-select v-model:value="searchForm.userId" :options="formattedOptions"
							:filter-option="filterOption" show-search style="width: 100%" placeholder="请选择" allow-clear
							@change="fzForm">
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-tabs v-model:activeKey="activeTabsKey">
				<a-tab-pane key="1" tab="基础信息" force-render>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="账号：" name="account">
								<a-input v-model:value="formData.account" placeholder="请输入账号" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="姓名：" name="name">
								<a-input v-model:value="formData.name" placeholder="选择组织后自动带出" readonly allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="性别：" name="gender">
								<a-radio-group v-model:value="formData.gender" :options="genderOptions"></a-radio-group>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="昵称：" name="nickname">
								<a-input v-model:value="formData.nickname" placeholder="请输入昵称" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="手机号：" name="phone">
								<a-input v-model:value="formData.phone" placeholder="请输入手机" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="邮箱：" name="email">
								<a-input v-model:value="formData.email" placeholder="请输入邮箱" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="出生日期：" name="birthday">
								<a-date-picker v-model:value="formData.birthday" value-format="YYYY-MM-DD"
									style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="员工编号：" name="empNo">
								<a-input v-model:value="formData.empNo" placeholder="请输入员工编号" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="组织ID：" name="deptId">
								<a-input v-model:value="formData.deptId" placeholder="自动带出" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="岗位ID：" name="siteId">
								<a-input v-model:value="formData.siteId" placeholder="自动带出" />
							</a-form-item>
						</a-col>
					</a-row>
				</a-tab-pane>
				<a-tab-pane key="2" tab="更多信息" force-render>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="民族：" name="nation">
								<a-select v-model:value="formData.nation" placeholder="请选择民族"
									:options="nationOptions"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="籍贯：" name="nativePlace">
								<a-input v-model:value="formData.nativePlace" placeholder="请输入籍贯" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="家庭住址：" name="homeAddress">
								<a-textarea v-model:value="formData.homeAddress" placeholder="请输入家庭住址"
									:auto-size="{ minRows: 2, maxRows: 5 }" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="通信地址：" name="mailingAddress">
								<a-textarea v-model:value="formData.mailingAddress" placeholder="请输入通信地址"
									:auto-size="{ minRows: 2, maxRows: 5 }" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="证件类型：" name="idCardType">
								<a-select v-model:value="formData.idCardType" placeholder="请选择证件类型"
									:options="idcardTypeOptions">
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="证据号码：" name="idCardNumber">
								<a-input v-model:value="formData.idCardNumber" placeholder="请输入通信地址" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="文化程度：" name="cultureLevel">
								<a-select v-model:value="formData.cultureLevel" placeholder="请选择文化程度"
									:options="cultureLevelOptions">
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="政治面貌：" name="politicalOutlook">
								<a-input v-model:value="formData.politicalOutlook" placeholder="请输入政治面貌" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="毕业学校：" name="college">
								<a-input v-model:value="formData.college" placeholder="请输入毕业学校" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="学历：" name="education">
								<a-input v-model:value="formData.education" placeholder="请输入学历" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="学制：" name="eduLength">
								<a-input v-model:value="formData.eduLength" placeholder="请输入学制" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="学位：" name="degree">
								<a-input v-model:value="formData.degree" placeholder="请输入学位" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="家庭电话：" name="homeTel">
								<a-input v-model:value="formData.homeTel" placeholder="请输入家庭电话" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="办公电话：" name="officeTel">
								<a-input v-model:value="formData.officeTel" placeholder="请输入办公电话" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="紧急联系人：" name="emergencyContact">
								<a-input v-model:value="formData.emergencyContact" placeholder="请输入紧急联系人" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="紧急联系电话：" name="emergencyPhone">
								<a-input v-model:value="formData.emergencyPhone" placeholder="请输入紧急联系电话" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="紧急联系人地址：" name="emergencyAddress">
								<a-textarea v-model:value="formData.emergencyAddress" placeholder="请输入紧急联系人地址"
									:auto-size="{ minRows: 2, maxRows: 5 }" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
				</a-tab-pane>
			</a-tabs>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="formLoading" @click="onSubmit">保存</a-button>
		</template>
	</a-drawer>
</template>

<script setup>
import userApi from '@/api/sys/userApi'
import bizRoleApi from '@/api/biz/bizRoleApi'
import { required, rules } from '@/utils/formRules'
// 默认是关闭状态
let visible = $ref(false)
const formRef = ref()
const activeTabsKey = ref('1')
const { proxy } = getCurrentInstance()
const emit = defineEmits({ successful: null })
const formLoading = ref(false)
const treeData = ref([])
const treeDefaultExpandedKeys = ref([])
import { cloneDeep, debounce } from 'lodash-es'
// 主职职位数据
let positionData = ref([])
// 主职主管人员数据
let directorData = ref([])

// 表单数据
let formData = ref({})


// 用于搜索的form
let searchForm = reactive({})

// onMounted(() => {
// 	getDeptTree()
// })
const params = reactive({
	level: '0',
	deptId: '0000'
})
const getDeptTree = async () => {
	try {
		const res = await bizRoleApi.deptTree(params)
		treeData.value = res
	} catch (error) {
		console.log(error)
	}
}

// 打开抽屉
const onOpen = (record) => {
	getDeptTree()
	visible = true
	formData.value = {
		gender: '男'
	}
	if (record) {
		convertFormData(record)
	}
}
const filterOption = (input, option) => {
	return option.orgName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
// 根据姓名查找组织
const accountList = ref([])
const getUUlist = (value) => {
	userApi.addUserlist({ searchKey: searchForm.account, deptId: searchForm.deptId }).then((data) => {
		if (data !== null) {
			accountList.value = cloneDeep(data)
		}
	})
}
const formattedOptions = computed(() => {
	return accountList.value.map(item => ({
		...item,
		label: `${item.userTruename} (${item.userId}) (${item.siteType == 1 ? '主岗' : item.siteType == 2 ? '兼职' : '借调'})`,
		value: item.userId
	}));
});
const handleBlur = () => {
	if (!searchForm.account || !searchForm.deptId) return
	searchForm.userId = null
	getUUlist()
}
const debouncedHandleBlur = debounce(handleBlur, 500); // 500毫秒后触发

const fzForm = (value) => {
	if (!value) return
	const findObj = accountList.value.find(v => v.userId === value);
	if (findObj) {
		formData.value.account = findObj.userId;
		formData.value.name = findObj.userTruename;
		formData.value.deptId = findObj.deptId;
		formData.value.siteId = findObj.siteId;
	}
}


// 关闭抽屉
const onClose = () => {
	treeData.value = []
	treeDefaultExpandedKeys.value = []
	positionData.value = []
	directorData.value = []
	searchForm = {}
	visible = false
}
// 回显数据
const convertFormData = (record) => {
	const param = {
		id: record.id
	}
	// 查询详情
	userApi.userDetail(param).then((data) => {
		formData.value = Object.assign(formData.value, data)
		formData.value.deptId = data.orgId;
	})
}
// 默认要校验的
const formRules = {
	account: [required('请输入账号')],
	name: [required('请输入姓名')],
	sex: [required('请选择性别')],
	siteId: [required('请选择组织')],
	deptId: [required('请输入')]
	// positionId: [required('请选择职位')]
}


// 验证并提交数据
const onSubmit = () => {
	formRef.value.validate().then(() => {
		let formDatas = JSON.parse(JSON.stringify(formData.value))
		formLoading.value = true
		userApi
			.submitForm(formDatas, !formDatas.id)
			.then(() => {
				onClose()
				emit('successful')
			})
			.finally(() => {
				formLoading.value = false
			})
	})
}
// 性别
const genderOptions = proxy.$TOOL.dictTypeList('GENDER').map((item) => {
	return {
		value: item['dictValue'],
		label: item['name']
	}
})
// 民族
const nationOptions = proxy.$TOOL.dictTypeList('NATION').map((item) => {
	return {
		value: item['dictValue'],
		label: item['name']
	}
})
// 身份证件
const idcardTypeOptions = proxy.$TOOL.dictTypeList('IDCARD_TYPE').map((item) => {
	return {
		value: item['dictValue'],
		label: item['name']
	}
})
// 文化程度
const cultureLevelOptions = proxy.$TOOL.dictTypeList('CULTURE_LEVEL').map((item) => {
	return {
		value: item['dictValue'],
		label: item['name']
	}
})

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
	onOpen
})
</script>

<style scoped type="less">
.childAddButton {
	margin-bottom: 10px;
}

.form-row {
	background-color: var(--item-hover-bg);
	margin-left: 0px !important;
}

.form-row-con {
	padding-bottom: 5px;
	padding-top: 5px;
	padding-left: 15px;
}

.dashedButton {
	margin-top: 10px;
	width: 100%;
}

.form-div {
	padding-top: 10px;
}
</style>
